<template>
  <div class="employee-container">
    <page-tools>
      <template #left>
        <span>总记录数: {{ total }} 条</span>
      </template>
      <!-- 使用右侧插槽 v-allow="'export_excel'" -->
      <template #right>
        <el-button v-allow="'import_excel'" type="warning" size="small" @click="showExcelDialog = true">导入excel</el-button>
        <el-button v-allow="'export-excel'" type="danger" size="small" @click="exportExcel">导出excel</el-button>
        <el-button v-allow="'add-employee'" type="primary" size="small" @click="$router.push(`/employee/empDetail`)">新增员工</el-button>
      </template>
    </page-tools>

    <!-- 表格位置 -->
    <el-card style="margin-top: 10px">
      <el-table border :data="empList">
        <el-table-column label="序号" type="index" />
        <el-table-column label="头像" align="center">
          <template #default="{ row }">
            <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
            <!-- <img v-if="row.staffPhoto" class="avatar" :src="row.staffPhoto" /> -->
            <!-- <img v-else class="avatar" src="@/assets/common/bigUserHeader.png" /> -->
            <span v-else class="avatar">{{ setNameAvatar(row.username) || 'H' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="username" label="姓名" />
        <el-table-column align="center" prop="mobile" label="手机号" />
        <el-table-column align="center" prop="workNumber" label="工号" />
        <el-table-column align="center" label="聘用形式">
          <template v-slot="{ row }">
            {{ hireType[row.formOfEmployment] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="departmentName" label="部门" />
        <el-table-column sortable align="center" prop="timeOfEntry" label="入职时间" />
        <el-table-column label="操作" width="200px" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employee/empDetail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
            <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配角色的dialog  -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <assign-role v-if="showRoleDialog" :id="currentId" @hCancel="showRoleDialog=false" />
    </el-dialog>
    <!-- 分页组件 -->
    <el-row type="flex" justify="center" align="middle" style="height: 60px">
      <el-pagination :current-page="q.page" :page-sizes="[5, 8, 10, 15]" :page-size="q.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="hSizeChange" @current-change="hCurrentChange" />
    </el-row>
    <!-- 导入excel  -->
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @success="hExcelSuccess" />
  </div>
</template>

<script>
import { delEmployee, getEmpList } from '@/api/employees'
import EmployeeConst from '@/constant/employees'
import { transExcelHeader } from '@/utils'
import assignRole from './assignRole.vue'

// import fileSaver from 'file-saver'

// // 把数组转成  obj:{'1':'正式', '2':'非正式'}，然后用obj["1"]就可以获取到,不用放到formOfEmployment函数里面，不用每次都循环
// const hireType = {}
// EmployeeConst.hireType.map(ele => (hireType[ele.id] = ele.value))
// console.log(hireType)
export default {
  name: 'Employee',
  components: { assignRole },
  data() {
    return {
      total: 0,
      q: {
        page: 1,
        pagesize: 5
      },
      currentId: 0,
      empList: [],
      hireType: {},
      showRoleDialog: false,
      showExcelDialog: false
    }
  },
  created() {
    this.loadGetEmployeesList()
    // 方式二，因为全局的数据，data是无法访问到的，所以写到created里面
    EmployeeConst.hireType.map(ele => (this.hireType[ele.id] = ele.value))
  },
  methods: {
    // 获取员工列表
    async loadGetEmployeesList() {
      const { data } = await getEmpList(this.q)
      // console.log(data)
      // const re = transExcelHeader(data)
      // console.log(re)
      this.total = data.total
      this.empList = data.rows
    },
    // 点击删除员工
    async hDel(id) {
      try {
        // 提示用户是否删除
        await this.$confirm('您确认要删除吗?', '提示', { type: 'warning' })
        // 发请求
        const res = await delEmployee(id)
        // 提醒用户
        this.$message.success(res.message)
        // 要先判断是不是当前的最后一条
        if (this.empList.length === 1 && this.q.page > 1) this.q.page--
        // 更新数据
        this.loadGetEmployeesList()
      } catch (error) {
        if (error === 'cancel') return
        this.$message.error(error.message)
      }
    },

    // 点击分配角色
    hAssign(id) {
      this.showRoleDialog = true
      this.currentId = id
    },

    // 子组件传过来，导入excel
    hExcelSuccess() {
      // 新增的数据要在最后一页显示
      // 如果刚好满一页，total要加1
      // if (this.total % this.q.pagesize === 0) this.total++
      // this.q.page = Math.ceil(this.total / this.q.pagesize)
      this.loadGetEmployeesList()
    },
    // 处理页码大小
    hSizeChange(val) {
      this.q.pagesize = val
      this.loadGetEmployeesList()
    },
    // 当前页变动时候触发的事件
    hCurrentChange(val) {
      this.q.page = val
      this.loadGetEmployeesList()
    },
    // 取名字作为头像的函数
    setNameAvatar(name) {
      if (name.startsWith('黑马')) {
        return name.slice(2, 3)
      } else {
        return name.slice(0, 1)
      }
    },

    // 导出excel
    async exportExcel() {
      // 发请求获取所有的数据
      const { data } = await getEmpList({ page: 1, pagesize: this.total })
      // console.log(data)
      this.hExportExcel(data)
    },
    // 再封装一个导出的数据
    async hExportExcel(list) {
      // 利用花裤衩写的组件导出excel
      if (!list.rows[0]) return
      // 把表头改为中文的
      const hdata = transExcelHeader(list)
      // 如果有数据的话就取出header
      const header = Object.keys(hdata[0])
      const data = hdata.map(ele => Object.values(ele))

      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        // header: ['姓名', '性别'], // 表头 必填
        // data: [ ['刘备', '男'],['关羽', '男'] ],  具体数据，是个二维数组 必填
        header,
        data,
        filename: '导出员工', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  height: 45px;
  width: 45px;
  border-radius: 50%;
  line-height: 45px;
  text-align: center;
  color: #fff;
  background-color: #04c9be;
  font-size: 12px;
  display: inline-block;
}
</style>
